package com.hs.egova.dao.impl;

import com.hs.egova.dao.JdbcTemplUserDao;
import com.hs.egova.mapping.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.util.List;

/**
 * @author husheng
 * @version v1.0
 * @date 2021/7/21 14:43
 * @email husheng@egova.com.cn
 */
@Repository
public class JdbcTemplUserDaoImpl implements JdbcTemplUserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserById(Long id) {
        String sql = "select * from t_user where id = ?";
        Object[] params = new Object[]{id};
        User user = jdbcTemplate.queryForObject(sql, getUserMapper(), params);
        return user;
    }

    @Override
    public List<User> listUser(String userName) {
        String sql = " select * from t_user where user_name like concat('%', ?, '%')";
        Object[] params = new Object[]{userName};
        List<User> users = jdbcTemplate.query(sql, getUserMapper(), params);
        return users;
    }

    private RowMapper<User> getUserMapper() {
        //使用Lambda
        RowMapper<User> userRowMapper = (ResultSet rs, int rownum) -> {
            User user = new User();
            user.setUserName(rs.getString("user_name"));
            user.setId(rs.getLong("id"));
            user.setNote(rs.getString("note"));
            return user;
        };
        return userRowMapper;
    }
}
